package com.ruoyi.client.cloudcc.bean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * CloudCC参数对象
 */
public class CloudCCFormData {
    //对象名
    private String objectApiName;

    /**
     * 数据
     */
    private JSONArray data = new JSONArray();

    /**
     * 当前操作行
     */
    private JSONObject curRow = new JSONObject();

    /**
     * @param objectApiName 对象名
     */
    public CloudCCFormData(String objectApiName){
        this.objectApiName = objectApiName;
        data.add(curRow);
    }

    public void setObjectApiName(String objectApiName){
        this.objectApiName = objectApiName;
    }

    public String getObjectApiName() {
        return objectApiName;
    }

    /**
     * 生成新的行
     * @return
     */
    public CloudCCFormData next(){
        if(!curRow.isEmpty()){
            curRow = new JSONObject();
            data.add(curRow);
        }
        return this;
    }

    /**
     * 生成新的行,设置新行第一个参数
     * @return
     */
    public CloudCCFormData next(String field,Object value){
        if(!curRow.isEmpty()){
            curRow = new JSONObject();
            curRow.put(field,value);
            data.add(curRow);
        }
        return this;
    }

    /**
     * 添加行数据
     * @param field
     * @param value
     * @return
     */
    public CloudCCFormData addField(String field,Object value){
        curRow.put(field,value);
        return this;
    }

    /**
     * 添加行数据,如果当前和存在相同数据则会替换字段值
     * @param row
     * @return
     */
    public CloudCCFormData addRow(JSONObject row) {
        curRow.putAll(row);
        return this;
    }

    /**
     * 设置行,如果上一行的数据没有保存，则会自动保存
     * @param row
     * @return
     */
    public CloudCCFormData setRow(JSONObject row){
        this.next();
        curRow.clear();
        curRow.putAll(row);
        return this;
    }

    /**
     * 设置行,如果上一行的数据没有保存，则会自动保存
     * @param row
     * @return
     */
    public CloudCCFormData setRow(Map<String,Object> row){
        this.next();
        curRow.clear();
        curRow.putAll(row);
        return this;
    }

    /**
     * 获取容器数据
     * @return
     */
    public JSONArray getData(){
        return this.data;
    }

    /**
     * 设置数据容器
     * @param data
     */
    public void setData(JSONArray data){
        this.data = data;
    }


    public static void main(String[] args) {
        CloudCCFormData form = new CloudCCFormData("test");
        form.addField("name","张三").addField("sex","男")
                .next("id",1)
                .addField("name","赵柳").addField("sex","女")
                .next("id",2)
                .addRow(JSON.parseObject("{'name':'张三'}"));
        System.out.println(form.getData().toJSONString());
    }
}
